/**
 * @(#)FeedController.java, 2010-5-19. 
 * 
 * Copyright 2010 Youdao, Inc. All rights reserved.
 * YOUDAO PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.rsstuan.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

import com.rsstuan.data.TuanGouWebItem;
import com.rsstuan.service.ChannelService;
import com.rsstuan.storage.data.TuanGouChannelData;
import com.rsstuan.storage.data.TuanGouItemData;
import com.rsstuan.storage.impl.JDOTuanGouChannelStorage;
import com.rsstuan.storage.impl.JDOTuanGouItemStorage;
import com.rsstuan.utils.ItemUtils;
import com.rsstuan.utils.StringUtils;

/**
 *
 * @author guosq
 *
 */
public class FeedController extends SpringController {
    
    
    private String FEED_VM = "feed/feed";
    public ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response) {
       
        JDOTuanGouItemStorage itemStorage = new JDOTuanGouItemStorage();
      
        Map<Long, TuanGouChannelData> channelMap = ChannelService.getInstance().getAllChannelsMap();
        List<TuanGouItemData> items = itemStorage.getActivateItems();
        List<TuanGouWebItem> webItems = new ArrayList<TuanGouWebItem>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (TuanGouItemData item : items) {
            if (ItemUtils.validate(item)) {
                TuanGouWebItem witem = new TuanGouWebItem(item);
                TuanGouChannelData channel = channelMap.get(item.getChannelId());
                if (channel != null)
                    witem.setSiteName(channel.getTitle());
                
                StringBuilder sb = new StringBuilder();
                sb.append("<p><img src=\"" + witem.getImage() + "\"/></p>");
                sb.append("<p>原价：<b>¥" + witem.getOrigPrice() + "</b></p>");
                sb.append("<p>现价：<b>¥" + witem.getPrice() + "</b></p>");
                sb.append("<p>折扣：<b>¥" + witem.getDiscount() + "</b></p>");
                sb.append("<p>节省：<b>¥" + witem.getSavePrice() + "</b></p>");
                witem.setFeedDescription(sb.toString());
                witem.setRssPubTime(sdf.format(item.getPubTime()));
                webItems.add(witem);
            }
        }
        
        TuanGouWebItem[] witemArray = webItems.toArray(new TuanGouWebItem[0]);
    
      
        //Map<String, Object> map = new HashMap<String, Object>();
        return createModelAndView(request, response, FEED_VM,
                "items", witemArray,
                "pubDate", sdf.format(new Date(System.currentTimeMillis())));
         
    
    }
    

}
